package ar.edu.itba.it.poo

class InssuficcientFoundsException extends Exception

class Account(val number: String, val owner: String) {

    private var f: Int = 0

    def founds = f

    def credit(ammount: Int) {
        require(ammount > 0)
        f += ammount
    }

    def debit(ammount: Int) {
        if (!canDebit(ammount)) throw new InssuficcientFoundsException()

        f -= ammount
    }

    def transfer(that: Account, ammount: Int) {
        debit(ammount)
        that.credit(ammount)
    }

    def drawCheck(ammount: Int): Check = new Check(this, ammount)
    def cashCheck(check: Check) {
        if (!check.canCash) throw new InssuficcientFoundsException()

        check.account.debit(check.ammount)
        credit(check.ammount)
    }
    def canDebit(ammount: Int): Boolean = founds >= ammount
}

class Check(val account: Account, val ammount: Int) {
    require(ammount > 0)

    def canCash = account.canDebit(ammount)
}

object AccountTest extends Application {

    val account1 = new Account("34-123/4", "Bob")
    val account2 = new Account("93-792/9", "Alice")

    account1.credit(100)
    account2.credit(200)

    account1.transfer(account2, 50)
    account2.debit(25)

    println(account1.founds);
    println(account2.founds);

    try {
        account1.transfer(account2, 100)
    } catch {
        case ex: InssuficcientFoundsException => println("Insufficient founds")
    }

    val account3 = new Account("34-123/4", "Bob");
    val account4 = new Account("93-792/9", "Alice");

    account3.credit(50);
    val check1 = account3.drawCheck(200);
    account3.credit(300);

    try {
        account4.cashCheck(check1)
    } catch {
        case ex: InssuficcientFoundsException => println("Insufficient founds")
    }

    println(account3.founds);
    println(account4.founds);

    val check2 = account3.drawCheck(300);

    try {
        account4.cashCheck(check2)
    } catch {
        case ex: InssuficcientFoundsException => println("Insufficient founds")
    }
}